/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86186
 * Date: 2023-07-24
 * Time: 22:02
 */
public class Test {

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */

      static class ListNode {
          int val;
          ListNode next;
          ListNode() {}
          ListNode(int val) { this.val = val; }
          ListNode(int val, ListNode next) { this.val = val; this.next = next; }
      }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null;
        ListNode cur = null;
        int tmp = 0;
        while(l1 != null || l2 != null) {
            int num1 = (l1 == null ? 0 : l1.val);
            int num2 = (l2 == null ? 0 : l2.val);
            int sum = num1 + num2 + tmp;
            if(head == null) {
                head = new ListNode(sum % 10);
                cur = head;
            }else {
                cur.next = new ListNode(sum % 10);
                cur = cur.next;
            }
            tmp = sum / 10;
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        if(tmp > 0) {
            cur.next = new ListNode(tmp);
        }
        return head;
    }
}
